package org.cosmact.designer.vxml.model.persistence.impl;

import java.io.IOException;
import java.util.Collections;

import org.cosmact.designer.vxml.model.persistence.IModelPersistence;
import org.cosmact.vxml.model.Document;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

/**
 * 
 * 
 *@author YeXiaowei 234aini@gmail.com
 * 
 */
public class EMFPersistence implements IModelPersistence {

    private org.eclipse.emf.common.util.URI createURIFromFileLocation(
	    final String location) {
	org.eclipse.emf.common.util.URI uri = org.eclipse.emf.common.util.URI
		.createURI(location);
	return uri;
    }

    @Override
    public Document read(String location) {
	if (location == null) {
	    throw new IllegalArgumentException("File empty");
	}

	ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
		.put(Resource.Factory.Registry.DEFAULT_EXTENSION,
			new XMIResourceFactoryImpl());
	org.eclipse.emf.common.util.URI uri = createURIFromFileLocation(location);
	Resource resource = resourceSet.getResource(uri, true);
	Document document = (Document) resource.getContents().get(0);
	return document;
    }

    @Override
    public void save(Document document, String location) throws IOException {
	// Create a resource set.
	ResourceSet resourceSet = new ResourceSetImpl();

	// Register the default resource factory -- only needed for stand-alone!
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
		.put(Resource.Factory.Registry.DEFAULT_EXTENSION,
			new XMIResourceFactoryImpl());

	// Create a resource for this file.
	Resource resource = resourceSet
		.createResource(createURIFromFileLocation(location));

	resource.getContents().add(document);

	// Save the contents of the resource to the file system.
	resource.save(Collections.EMPTY_MAP);
    }
}
